package testProject;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.onpositive.page.pagerendering.CommitPageRenderer;
import com.onpositive.page.pagerendering.SiteContentRenderer;
import com.onpositive.page.pagerendering.interfaces.ISiteContentRenderer;
import com.onpositive.storage.managers.MemoryFileItemFactory;
import com.onpositive.storage.managers.UnifiedContentProvider;

@SuppressWarnings("serial")
public class UploadingServlet extends HttpServlet {

	private static ISiteContentRenderer iscr = SiteContentRenderer
			.getSiteContentRenderer();

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		CommitPageRenderer cr = new CommitPageRenderer();
		String content = cr.getContent("commit.upload", "file");
		iscr.initRenderer(getServletContext());
		InputStreamReader is = new InputStreamReader(new ByteArrayInputStream(
				content.getBytes()));
		((SiteContentRenderer) iscr).render(resp, is, "commit.page", false);

	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String str = req.getRequestURI();
		if (str.endsWith(".upload")) {
			str = str.substring(0, str.length() - ".upload".length());
		}
		str = "/commit.commit";
		ServletFileUpload sfu = new ServletFileUpload(
				new MemoryFileItemFactory());
		List lst = null;
		try {
			lst = sfu.parseRequest(req);
		} catch (FileUploadException e) {
			e.printStackTrace();
		}
		for (Object o : lst) {
			if (o instanceof FileItem) {
				FileItem item = (FileItem) o;
				if (item.getFieldName().equals("file")) {

					String mappedName = item.getName();
					mappedName = "/" + mappedName;

					String contentType = item.getContentType();
					if (contentType.indexOf("image") != -1) {
						mappedName = "/images" + mappedName;
					} else if (contentType.indexOf("text/css") != -1) {
						mappedName = "/res" + mappedName;
					}
					ByteArrayOutputStream bOs = new ByteArrayOutputStream();
					byte[] buff = new byte[1024];
					int count = 0;
					InputStream iss = item.getInputStream();
					while ((count = iss.read(buff)) != -1) {
						bOs.write(buff, 0, count);
					}

					UnifiedContentProvider.storeContentElement(mappedName, bOs.toByteArray());
					bOs.close();
					iss.close();
				}
			}
		}

		resp.sendRedirect(str);
	}

}
